package com.ufaud.ais.pub.utils;

import java.util.Comparator;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
import org.apache.commons.collections.comparators.NullComparator;
import org.apache.commons.lang.ArrayUtils;

public class ComparisonUtil {

	private ComparisonUtil(){}
	
	/**
	 * 功能: 取得一个能以集合元素的一系列字段排序的Set
	 * @author 林可  2010-9-1 下午01:58:08
	 * @param <T> 元素的泛型
	 * @param propertyNames 排序字段名
	 * @param arr_isInverse 是否反转默认顺序（一般都是转为降序），默认都为false
	 * @param arr_nullsAreHigh 若字段为空值，是否为大，默认都为false
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> Comparator<T> getBeanPropertyComparator(String[] propertyNames, boolean[] arr_isInverse, boolean[] arr_nullsAreHigh) {
		
		if (ArrayUtils.isEmpty(arr_isInverse)) {
			arr_isInverse = new boolean[propertyNames.length];
		} else if (arr_isInverse.length != propertyNames.length) {
			throw new IllegalArgumentException("数组参数arr_isInverse的长度与第一个参数不一致");
		}
		
		if (ArrayUtils.isEmpty(arr_nullsAreHigh)) {
			arr_nullsAreHigh = new boolean[propertyNames.length];
		} else if (arr_nullsAreHigh.length != propertyNames.length) {
			throw new IllegalArgumentException("数组参数arr_nullsAreHigh的长度与第一个参数不一致");
		}

		ComparatorChain cc = new ComparatorChain();
		int ccLength = propertyNames.length;
		for (int i = 0; i < ccLength; i++) {
			String orderField = propertyNames[i];
			boolean isInverse = arr_isInverse[i];
			boolean nullsAreHigh = arr_nullsAreHigh[i];
			Comparator c = new NullComparator(new BeanComparator(orderField), nullsAreHigh);
			cc.addComparator(c, isInverse);
		}
		return cc;
	}
}
